package com.zhixing.web.service.impl;

import com.zhixing.web.common.constant.FieldDefaultValueConstant;
import com.zhixing.web.common.utils.FileUtil;
import com.zhixing.web.service.config.FilePathConfig;
import com.zhixing.web.service.exception.GlobalException;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author dzh
 * @version 1.0.0.05020
 * <p>project: d-blog</p>
 * <p>created time: 2022/05/09 15:32</p>
 * <p>describe: 本地文件 上传操作</p>
 * <p>remarks: </p>
 **/
@Service
public class FileLocalUploadService {

    private FilePathConfig filePathConfig;

    @Autowired
    public FileLocalUploadService(FilePathConfig filePathConfig) {
        this.filePathConfig = filePathConfig;
    }

    /**
     * <p>描述：本地文件上传</p>
     *
     * @author dzh
     * @param file 目标文件
     * @param folderName 指定保存的文件夹
     * @return 访问路径
     * <p>时间：2022/5/9 13:39</p>
     * <p>说明1：</p>
     * <p>说明2：</p>
     **/
    public String fileUpload (MultipartFile file, String folderName) {

        String extension = FilenameUtils.getExtension(file.getOriginalFilename());

        if (file.getSize() > FieldDefaultValueConstant.FILE_SIZE_LIMIT) {

            throw new GlobalException(-1, "文件过大");
        } else if (!"jpg".equals(extension) && !"png".equals(extension) && !"jpeg".equals(extension) && !"JPG".equals(extension) &&
                !"PNG".equals(extension) && !"gif".equals(extension) && !"GIF".equals(extension) && !"JPEG".equals(extension)) {

            throw new GlobalException(-1, "GlobalException");
        }

        String filePath = filePathConfig.getFilepath() + folderName;

        String fileName;

        try {

            fileName = FileUtil.uploadFile(file, filePath, false);

        } catch (Exception e) {

            throw new GlobalException(-1, "文件上传失败");
        }

        return filePathConfig.getUrl() + folderName + fileName;
    }
}
